<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>比赛预告 - 体育比分网</title>
    <script src="../common/js/tailwindcss.js"></script>
    <script src="../common/js/lucide.min.js"></script>
</head>
<body class="min-h-screen bg-gray-100">
<!-- 导航栏 -->
<nav class="bg-white shadow-md sticky top-0 z-40">
    <div class="max-w-7xl mx-auto px-4">
        <div class="flex justify-between items-center h-16">
            <div class="flex items-center">
                <button onclick="history.back()" class="p-2 rounded-md hover:bg-gray-100">
                    <i data-lucide="arrow-left"></i>
                </button>
                <span class="ml-4 text-xl font-bold">比赛预告</span>
            </div>
        </div>
    </div>
</nav>

<main class="max-w-7xl mx-auto px-4 py-6">
    <!-- 日期选择器 -->
    <div class="bg-white rounded-lg shadow-md p-4 mb-6" id="dateSelectorContainer">
        <div class="flex space-x-4 overflow-x-auto py-2">
            <!-- 日期选项将由 JS 动态生成 -->
        </div>
    </div>

    <!-- 联赛筛选 -->
    <div class="bg-white rounded-lg shadow-md p-4 mb-6" id="leagueFilterContainer">
        <div class="flex flex-wrap gap-2">
            <!-- 联赛选项将由 JS 动态生成 -->
        </div>
    </div>

    <!-- 比赛列表容器 -->
    <div id="matchesContainer">
        <!-- 加载状态 -->
        <div id="loadingSpinner" class="text-center py-8">
            <div class="inline-block animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500"></div>
        </div>

        <!-- 比赛列表 -->
        <div id="matchList" class="space-y-4">
            <!-- 比赛内容将由 JS 动态生成 -->
        </div>
    </div>
</main>

<script>
    const API_KEY = '68e3b6a93705d8742e8b67a6861842ab';
    let selectedDate = new Date().toISOString().split('T')[0];
    let selectedLeague = 'all';

    // 热门联赛列表
    const POPULAR_LEAGUES = {
        39: { name: '英超', logo: 'https://www.scorebat.com/og/flag/default/epl.png' },
        140: { name: '西甲', logo: 'https://www.scorebat.com/og/flag/default/laliganew.png' },
        135: { name: '意甲', logo: 'https://www.scorebat.com/og/flag/default/seriea.png' },
        78: { name: '德甲', logo: 'https://www.scorebat.com/og/flag/default/bundesliga.png' },
        61: { name: '法甲', logo: 'https://www.scorebat.com/og/flag/default/ligue1A.png' }
    };

    // 初始化日期选择器
    function initDateSelector() {
        const container = document.querySelector('#dateSelectorContainer > div');
        if (!container) return;

        const dates = [];
        for (let i = 0; i < 15; i++) {
            const date = new Date();
            date.setDate(date.getDate() + i);
            dates.push({ date, index: i });
        }

        container.innerHTML = dates.map(({date, index}) => {
            const dateStr = date.toISOString().split('T')[0];
            const isToday = index === 0;
            const isTomorrow = index === 1;
            const isSelected = dateStr === selectedDate;

            return `
                    <button
                        onclick="changeDate('${dateStr}')"
                        class="flex-shrink-0 px-4 py-2 rounded-lg ${
                isSelected
                    ? 'bg-blue-500 text-white'
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
            }"
                    >
                        <div class="text-sm font-medium">${
                isToday
                    ? '今天'
                    : isTomorrow
                        ? '明天'
                        : date.toLocaleDateString('zh-CN', { weekday: 'short' })
            }</div>
                        <div class="text-sm">${
                date.toLocaleDateString('zh-CN', { month: 'numeric', day: 'numeric' })
            }</div>
                    </button>
                `;
        }).join('');
    }

    // 初始化联赛筛选器
    function initLeagueFilter() {
        const container = document.querySelector('#leagueFilterContainer > div');
        if (!container) return;

        container.innerHTML = `
                <button
                    onclick="changeLeague('all')"
                    class="px-4 py-2 rounded-lg ${
            selectedLeague === 'all'
                ? 'bg-blue-500 text-white'
                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
        }"
                >
                    全部联赛
                </button>
                ${Object.entries(POPULAR_LEAGUES).map(([id, league]) => `
                    <button
                        onclick="changeLeague('${id}')"
                        class="flex items-center px-4 py-2 rounded-lg ${
            selectedLeague === id
                ? 'bg-blue-500 text-white'
                : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
        }"
                    >
                    <img src="${league.logo}" alt="${league.name}" class="w-4 h-4 mr-2"/>
                        ${league.name}
                    </button>
                `).join('')}
            `;
    }

    // 获取比赛预告
    async function fetchMatches() {
        const spinner = document.getElementById('loadingSpinner');
        const matchList = document.getElementById('matchList');

        if (!spinner || !matchList) return;

        try {
            spinner.style.display = 'block';
            matchList.innerHTML = '';

            const leagueParam = selectedLeague === 'all'
                ? Object.keys(POPULAR_LEAGUES).join('-')
                : selectedLeague;

            const response = await fetch(
                `https://v3.football.api-sports.io/fixtures?date=${selectedDate}&league=${leagueParam}`,
                {
                    headers: {
                        'x-rapidapi-host': 'v3.football.api-sports.io',
                        'x-rapidapi-key': API_KEY
                    }
                }
            );

            const data = await response.json();

            if (!data.response || data.response.length === 0) {
                matchList.innerHTML = `
                        <div class="text-center py-8 text-gray-500">
                            当日暂无比赛
                        </div>
                    `;
                return;
            }

            // 按联赛分组渲染比赛
            const matches = data.response.sort((a, b) =>
                new Date(a.fixture.date) - new Date(b.fixture.date)
            );

            matchList.innerHTML = matches.map(match => `
                    <div class="bg-white rounded-lg shadow-md overflow-hidden">
                        <div class="p-4 hover:bg-gray-50">
                            <div class="flex justify-between items-center">
                                <div class="flex-1">
                                    <div class="flex items-center">
                                        <span class="font-medium">${match.teams.home.name}</span>
                                    </div>
                                    <div class="flex items-center mt-2">
                                        <span class="font-medium">${match.teams.away.name}</span>
                                    </div>
                                </div>
                                <div class="text-center">
                                    <div class="text-sm text-gray-500">
                                        ${new Date(match.fixture.date).toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit'
            })}
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                `).join('');

        } catch (error) {
            console.error('Error fetching matches:', error);
            matchList.innerHTML = `
                    <div class="text-center py-8 text-red-500">
                        加载失败，请稍后重试
                    </div>
                `;
        } finally {
            spinner.style.display = 'none';
        }
    }

    // 切换日期
    function changeDate(date) {
        selectedDate = date;
        initDateSelector();
        fetchMatches();
    }

    // 切换联赛
    function changeLeague(league) {
        selectedLeague = league;
        initLeagueFilter();
        fetchMatches();
    }

    // 初始化页面
    document.addEventListener('DOMContentLoaded', () => {
        lucide.createIcons();
        initDateSelector();
        initLeagueFilter();
        fetchMatches();
    });
</script>
</body>
</html>
